<?php

namespace app\common\model\product;

use think\Model;

// 引入软删除模型
use traits\model\SoftDelete;

class Product extends Model
{
    // 调用软删除模型
    use SoftDelete;

    // 指定的数据表
    protected $name = 'product';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义创建时间字段
    protected $createTime = 'createtime';

    // 定义更新时间字段 => false 禁用
    protected $updateTime = false;

    // 定义软删除字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'thumb_cdn', // 商品单图
        'thumbs_cdn', // 商品多图
    ];

    public function getThumbCdnAttr($value, $data)
    {
        $thumbs = $data['thumbs'] ?? '';

        $domain = request()->domain();

        // 转成数组
        $thumbsArr = explode(',', $thumbs);

        $thumbsArr = array_filter($thumbsArr);

        $thumb = $thumbsArr[0] ?? '';

        if (!$thumb || !is_file('.' . $thumb)) {
            return $domain . '/assets/home/images/web.jpg';
        }
   
        return $domain . $thumb;
    }

    public function getThumbsCdnAttr($value, $data)
    {
        $thumbs = $data['thumbs'] ?? '';

        $domain = request()->domain();

        // 转成数组
        $thumbsArr = explode(',', $thumbs);

        $thumbsArr = array_filter($thumbsArr);

        $list = [];

        foreach ($thumbsArr as $val) {
            if ($val && is_file('.' . $val)) {
                $list[] = $domain . $val;
            }
        }

        if ($list) {
            return $list;
        } else {

            $list = [$domain . '/assets/home/images/web.jpg'];

            return $list;
        }
    }

    public function unit(){
        return $this->belongsTo('app\common\model\coupon\Coupon','unitid','id',[],'LEFT')->setEagerlyType(0);
    }
}
